/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fsktms.client;

import fsktms.IMessage;
import fsktms.Message;
import fsktms.dispatcher.DispatchSource;
import fsktms.messagemanager.IMessageManager;
import fsktms.messagemanager.IMessageSender;
import fsktms.messagemanager.MessageFactory;
import fsktms.packetmanager.PacketFactory;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author salm
 */
public class NetClient implements Runnable, IMessageSender, DispatchSource
{
    private Socket clientSocket;
    private IMessageManager mm;
    
    public NetClient(String serverAddress, int port) throws UnknownHostException, IOException
    {
        this.clientSocket = new Socket(serverAddress, port);
        this.mm = MessageFactory.createMM(PacketFactory.createPM(clientSocket));
    }

    @Override
    public boolean isClosed() {
        return mm.isClosed();
    }

    @Override
    public void close() throws IOException {
        mm.close();
    }
    
    public IMessageManager getMessages()
    {
        return this.mm;
    }

    @Override
    public void run()
    {
        mm.run();
    }

    @Override
    public void sendMessage(byte[] msgData, int magicKey)
    {
        this.mm.sendMessage(new Message(this.getClientSocket().getInetAddress().toString(), msgData, magicKey));
    }

    @Override
    public IMessage getCompletedMessage()
    {
        return this.mm.getCompletedMessage();
    }

    @Override
    public boolean isHasCompletedMessage()
    {
        return this.mm.isHasCompletedMessage();
    }

    /**
     * @return the clientSocket
     */
    public Socket getClientSocket() {
        return clientSocket;
    }
}